import Taro, { useDidShow } from '@tarojs/taro';
import { View, Text } from '@tarojs/components';
import { useEffect, useMemo, useState } from 'react';
import { contactStore } from '@/business/store/contact/contact';
import { friendAdd } from '@/business/services/contact';
import { fetchAddressByLocation } from '@/business/services/common/common';
import { findCity, flatCities, getLocationIds } from '@/utils/city';
import { cityTreeListStore } from '@/business/store/city/city';
import { useUserStore } from '@/business/store/user/login';
import { AtActionSheet, AtActionSheetItem } from 'taro-ui';
import SafePhoneModal from '@/components/SafePhoneModal';
import UserCard from '@/components/UserCard';
import ScrollList from '@/components/ScrollList';
import ChildrenTabs from '@/components/ChildrenTabs';
import EmptyPage from '@/components/EmptyPage';
import cssModule from './index.module.scss';
import SearchBox from '@/pages/index/components/SearchBox';

/**
 * @description 公开豹友
 * @author Shawn
 */

export default function PublicFriends(
  { cityCode, nearbyFriendsCount }: { cityCode: string, nearbyFriendsCount: number }
) {
  const useUser = useUserStore()

  const publicFriendList = contactStore((state) => state.publicFriendList);
  const isDataLoadedPublic = contactStore((state) => state.isDataLoadedPublic);
  const hasMorePublic = contactStore((state) => state.hasMore);

  const [currentPage, setCurrentPage] = useState(1);
  const [isOnline, setOnline] = useState(false);
  const [isVip, setVip] = useState(false);
  const [sameRegion, setSameRegion] = useState(false);

  const [location, setLocation] = useState('');
  const [locationIds, setLocationIds] = useState({
    provinceId: '',
    cityId: '',
    districtId: '',
  })

  const [regionId, setRegionId] = useState('');
  const childrenTabs = useMemo(() => [
    {
      name: '推荐',
      value: 'all',
    },
    {
      name: '在线',
      value: 'isOnline',
    },
    {
      name: '老乡',
      value: 'sameRegion',
    },
    {
      name: 'vip会员',
      value: 'isVip',
    }], []);

  // 切换地区
  const handleTabRegionChange = (regionId: string) => {
    setRegionId(regionId);
    getPublicFriendList(regionId);
  };

  // 子选项卡切换
  const handleTabChange = (tabValue: string) => {
    setOnline(tabValue === 'isOnline');
    setVip(tabValue === 'isVip');
    setSameRegion(tabValue === 'sameRegion');
    contactStore.getState().getPublicFriendList({ current: 1, size: 10 },
      tabValue === 'isOnline',
      tabValue === 'isVip',
      tabValue === 'sameRegion',
      regionId ? regionId : cityCode
    );
  }

  // 获取公开豹友名单
  const getPublicFriendList = async (regionId?: string) => {
    setCurrentPage(1);
    await contactStore.getState().getPublicFriendList({ current: 1, size: 10 },
      isOnline,
      isVip,
      sameRegion,
      regionId ? regionId : cityCode);
  }

  // 跳转到搜索公开豹友页面
  const handleSearch = () => {
    Taro.navigateTo(
      {
        url: `/subPackages/searchPublicFriend/index`
      }
    );
  };

  // 跳转到附近的豹友页面
  const handleNearByFriends = () => {
    if (useUser?.vipInfo?.vipLevelId !== '001') {
      Taro.navigateTo({
        url: `/subPackages/equity/index`,
      });
      return
    }
    Taro.navigateTo(
      {
        url: `/subPackages/nearbyFriends/index`
      }
    );
  }

  // 上拉加载
  const handleOnScrollToLower = async () => {
    if (publicFriendList.length % 10 !== 0) return;
    const nextPage = currentPage + 1;
    setCurrentPage(nextPage);
    await contactStore.getState().handlePullUpOrDownPublic({ current: nextPage, size: 10 },
      isOnline,
      isVip,
      sameRegion,
      regionId ? regionId : cityCode);
  };

  // 添加好友
  const handleAddFriend = async (item: any) => {
    if (useUser?.vipInfo?.vipLevelId !== '001') {
      Taro.navigateTo({
        url: `/subPackages/equity/index`,
      });
      return
    }
    const res = await friendAdd(
      { friendId: item.userId, remark: item.remark || '' }
    )
    if (res.success) {
      Taro.showToast({
        title: '添加好友请求已发送',
        icon: 'none',
        duration: 2000
      });
      contactStore.getState().changeFriendStatus(item.userId)
      // getPublicFriendList(regionId ? regionId : cityCode);
    } else {
      Taro.showToast({
        title: '添加好友请求发送失败，请稍后重试',
        icon: 'error',
        duration: 2000
      });
    }
  }

  // 获取当前城市
  const getLocation = async () => {
    const res = await Taro.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
    });
    const { latitude, longitude } = res;

    console.log('latitude === ', latitude);
    console.log('longitude === ', longitude);
    if (!latitude || !longitude) {
    } else {
      const location = await fetchAddressByLocation({
        latitude: latitude,
        longitude: longitude
      });
      setLocation(location);
      console.log('location data === ', location);

      const code = findCity(flatCities(cityTreeListStore.getState().cityTreeList), location.data.adcode)
      setRegionId(code);
      getPublicFriendList(code);
      const { provinceId, cityId, districtId } = getLocationIds(flatCities(cityTreeListStore.getState().cityTreeList), code)
      setLocationIds({
        provinceId,
        cityId,
        districtId,
      })
    }
  }

  const [isActionSheetOpened, setIsActionSheetOpened] = useState(false);
  const [isSafePhoneModalOpened, setIsSafePhoneModalOpened] = useState(false);
  const [contactMobile, setContactMobile] = useState(''); // 联系电话
  const [contactUserID, setContactUserID] = useState(''); // 用户userID

  // 个人空间
  const handlePerson = (item: any) => {
    console.log('点击用户卡片跳转用户详情===', item);
    // 点击用户卡片跳转用户详情
    if (useUser?.vipInfo?.vipLevelId === '001') {
      setIsActionSheetOpened(false);
      Taro.navigateTo({
        url: `/subPackages/userDetail/index?id=${contactUserID}`
      });
    } else {
      Taro.navigateTo({
        url: `/subPackages/equity/index`,
      });
    }
  };

  // 拨打电话
  const handleCall = () => {
    setIsActionSheetOpened(false);
    // setIsSafePhoneModalOpened(true);
    Taro.makePhoneCall({
      phoneNumber: contactMobile,
      success: () => {
      },
      fail: (err) => {
        console.error('拨打电话失败:', err)
        Taro.showToast({
          title: '拨打失败',
          icon: 'none'
        })
      }
    })
  };

  // 发送消息
  const handleSendMsg = () => {
    setIsActionSheetOpened(false);
    if (!contactUserID) return
    Taro.navigateTo({
      url: '/subPackages/chatlist/index' + `?conversationID=C2C${contactUserID}`
    })
  };

  const handleClick3 = (item: any) => {
    return () => {
      if (useUser?.vipInfo?.vipLevelId !== '001') {
        Taro.navigateTo({
          url: `/subPackages/equity/index`,
        });
        return
      }
      console.log(item, 'item')
      // setIsActionSheetOpened(true);
      // setContactUserID(item?.userId)
      // setContactMobile(item?.contactMobile);
      Taro.navigateTo({
        url: `/subPackages/userDetail/index?id=${item.userId}`
      })
    }

  };

  const [showPhone, setShowPhone] = useState(false);

  useDidShow(() => {
    cityCode = ''
  });

  useEffect(() => {
    getLocation();
  }, [])

  return (
    <View className={cssModule.container}>
      <View className={cssModule.listBox}>
        {/* 选项卡组件 */}
        <View className={cssModule.tabsBox}>
          {/* 搜索组件 */}
          <View className={cssModule.searchBox} onClick={handleSearch}>
            <SearchBox />
          </View>
          {/* 附近的豹友 */}
          <View className={cssModule.applyBox} onClick={handleNearByFriends}>
            <Text className={cssModule.applyTitle}>附近的豹友</Text>
            <Text className={cssModule.applyContent}>
              &gt;
            </Text>
          </View>
          <View className={cssModule.dividerLine} />
          {/* 子选项卡组件 */}
          <View className={cssModule.childrenTabs}>
            <ChildrenTabs type={'publicFriend'} childrenTabs={childrenTabs} location={location} locationIds={locationIds} onTabChange={handleTabChange} onRegionChange={handleTabRegionChange} isGetLocation={false} />
          </View>
          {/* 列表容器组件 */}
          <View className={cssModule.scrollList}>
            <ScrollList childrenNode={
              <>
                {
                  (!isDataLoadedPublic && (!publicFriendList || publicFriendList.length === 0)) ? (
                    <EmptyPage defaultName='' />
                  ) : (
                    publicFriendList?.map((item: any, idx: number) => (
                      <View className={cssModule.listViewCard} key={item.id ?? idx} onClick={handleClick3(item)}>
                        <UserCard item={item} btnName='加好友' handleClick={handleAddFriend} />
                      </View>
                    ))
                  )
                }
              </>
            }
              height={`100%`}
              onScrollToLower={handleOnScrollToLower}
              hasMore={hasMorePublic}
              isDataLoaded={isDataLoadedPublic}
            />
          </View>
        </View>
      </View>

      {/* 联系TA */}
      <AtActionSheet
        isOpened={isActionSheetOpened}
        cancelText='取消'
        onClose={() => setIsActionSheetOpened(false)}
        onCancel={() => setIsActionSheetOpened(false)}
      >
        <AtActionSheetItem onClick={handlePerson}>个人空间</AtActionSheetItem>
        {
          showPhone &&
          <AtActionSheetItem onClick={handleCall}>拨打对方电话</AtActionSheetItem>}
        <AtActionSheetItem onClick={handleSendMsg}>发送消息</AtActionSheetItem>
      </AtActionSheet>

      {/* 安全号弹窗 */}
      <SafePhoneModal
        contactMobile={contactMobile}
        isOpened={isSafePhoneModalOpened}
        onClose={() => setIsSafePhoneModalOpened(false)}
      />
    </View>
  )
}
